package com.huiyeji.hui.service.impl;

import com.huiyeji.hui.entity.Group;
import com.huiyeji.hui.exception.HuiException;
import com.huiyeji.hui.mapper.GroupMapper;
import com.huiyeji.hui.service.GroupService;
import com.huiyeji.hui.utils.ErrorEnum;
import com.huiyeji.hui.utils.PageUtil;
import com.huiyeji.hui.vo.PageResult;
import com.huiyeji.hui.vo.SelfAndOthersAndGroupsVo;
import com.huiyeji.hui.vo.SimpleGroupVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhaoduo
 */
@Service
public class GroupServiceImpl implements GroupService {

    private final GroupMapper mapper;

    @Autowired
    public GroupServiceImpl(GroupMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public List<SelfAndOthersAndGroupsVo.Group> getGroups(Long uid) {
        List<SelfAndOthersAndGroupsVo.Group> groups = mapper.getGroups(uid);
        groups.forEach(group -> {
            List<Long> others = mapper.getGroupOthers(group.getGid());
            group.setOtherIds(others);
        });
        return groups;
    }

    @Override
    public void changeGroupName(Long uid, Long gid, String groupName) {
        int row = mapper.changeGroupName(uid, gid, groupName);
        if (row != 1){
            throw new HuiException(ErrorEnum.MODIFY_ERROR);
        }
    }

    @Override
    public void changeGroupNotice(Long uid, Long gid, String notice) {
        int row = mapper.changeGroupNotice(uid, gid, notice);
        if (row != 1){
            throw new HuiException(ErrorEnum.MODIFY_ERROR);
        }
    }

    @Override
    public PageResult<SimpleGroupVo> keySearch(Long uid, PageUtil.KeyPageParam pp) {
        List<SimpleGroupVo> record = mapper.keySearch(uid,pp);
        return PageResult.build(1,1,record);
    }

    @Override
    public PageResult<SimpleGroupVo> conditionSearch(Long uid, PageUtil.GroupConditionPageParam pp) {
        int size = mapper.conditionSearchSize(uid,pp);
        List<SimpleGroupVo> record = mapper.conditionSearch(uid,pp);
        return PageResult.build(pp.getPageNum(),size,record);
    }

    @Override
    public void deleteGroup(Long uid, Long gid) {
        int row = mapper.deleteGroup(uid,gid);
        if (row != 1){
            throw new HuiException(ErrorEnum.DELETE_GROUP_ERROR);
        }
    }

    @Override
    public void createGroup(Group group) {
        int row = mapper.insertSelective(group);
        if (row != 1){
            throw new HuiException(ErrorEnum.CREATE_ERROR);
        }
    }

    @Override
    public SimpleGroupVo selectSimpleGroup(Long gid) {
        return mapper.getSimpleGroup(gid);
    }

    @Override
    public SelfAndOthersAndGroupsVo.Group getGroup(Long uid, Long gid) {
        return mapper.getGroup(uid,gid);
    }
}
